package com.xiaohei.security.filter;

import com.alibaba.fastjson2.JSON;
import com.xiaohei.common.JWT.JWTHelper;
import com.xiaohei.common.result.ResponseUtil;
import com.xiaohei.common.result.Result;
import com.xiaohei.common.result.ResultCodeEnum;
import com.xiaohei.security.custom.LoginUserInfoHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * ClassName: TokenAuthenticationFilter
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/5/1 22:05
 * Version 1.0
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        logger.info("uri:"+request.getRequestURI());
        //如果是登录接口，直接放行
        if("/admin/system/index/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if(null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.LOGIN_AUTH));
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //请求头中是否有token
        String token = request.getHeader("token");
        logger.info("token:"+token);
        //判断
        if(!StringUtils.isEmpty(token)){
            String username = JWTHelper.getUsername(token);
            if(!StringUtils.isEmpty(username)){
                //当前用户信息放到ThreadLocal里去
                LoginUserInfoHelper.setUserId(JWTHelper.getUserId(token));
                LoginUserInfoHelper.setUsername(username);
                //根据用户名称从redis中获取用户权限数据
                String authString =(String) redisTemplate.opsForValue().get(username);
                //把redis中的字符串转换成集合类型 List<SimpleGrantedAuthority>
                if(!StringUtils.isEmpty(authString)){
                    List<Map> mapList = JSON.parseArray(authString, Map.class);

                    List<SimpleGrantedAuthority> authList = new ArrayList<>();
                    for(Map map : mapList){
                        //把权限信息添加到集合中
                        authList.add(new SimpleGrantedAuthority((String) map.get("authority")));
                    }
                    return new UsernamePasswordAuthenticationToken(username,null, authList);
                }else {
                    return new UsernamePasswordAuthenticationToken(username,null, new ArrayList<>());
                }
            }
        }
        return null;
    }
}
